package com.hulk.rpc.transport.client.handler;

import com.hulk.rpc.serialize.Serializer;
import com.hulk.rpc.transport.client.codec.RequestEncoder;
import com.hulk.rpc.transport.client.codec.RequestListEncoder;
import com.hulk.rpc.transport.client.codec.ResponseDecoder;
import com.hulk.rpc.transport.client.future.FutureContainer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

import static com.hulk.rpc.config.common.HulkConstants.MAX_FRAME_LENGTH;

/**
 * @author xuxukang
 */
public class HulkChannelInitializer extends ChannelInitializer<SocketChannel> {
  private final Serializer serializer;

  public HulkChannelInitializer(Serializer serializer) {
    this.serializer = serializer;
  }

  @Override
  public void initChannel(SocketChannel ch) throws Exception {
    FutureContainer container = new FutureContainer();

    RequestEncoder requestEncoder = new RequestEncoder(serializer, container);
    RequestListEncoder requestListEncoder = new RequestListEncoder(serializer, container);
    ResponseDecoder decoder = new ResponseDecoder(MAX_FRAME_LENGTH, serializer, container);

    ch.pipeline()//
            .addLast("requestEncoder", requestEncoder)//
            .addLast("requestListEncoder", requestListEncoder)//
            .addLast("decoder", decoder);
  }
}
